package com.naihe.anderson.sms.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONObject;

public class HttpUtil {

	public static String getAddressInfo(String latLng) {
		String result = "";
		try {
	        StringBuilder stringBuilder = new StringBuilder();
	        BufferedReader in = null;
            URL url = new URL("http://maps.google.com/maps/api/geocode/json?latlng=" + latLng + "&language=zh-CN&sensor=true");
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setDoInput(true);
            in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));//注意，这里要声明字符编码是UTF-8，否则会乱码
            String line;
            while ((line = in.readLine()) != null) {
                stringBuilder.append(line);
            }
            in.close();
            JSONObject jsonObject = new JSONObject();
            jsonObject = new JSONObject(stringBuilder.toString());
            JSONArray results = jsonObject.getJSONArray("results");
            if (results.length() > 0) {
                result = ((JSONObject) results.get(0)).getString("formatted_address");

                if (result.indexOf("邮政编码") > 0) {
                    result = result.substring(0, result.indexOf("邮政编码"));
                }
                if (result.startsWith("中国"))
                    result = result.replace("中国", "");
            }
        } catch (Exception e) {
            FileUtil.addLog("", HttpUtil.class, "HttpUtil", e);
        }
        return result;
    }
}
